######################################
# 规则格网裁剪
######################################
import os
import sys

from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import QSettings, Qt, pyqtSignal, QDateTime, QDate
from PyQt5.QtGui import QPalette, QBrush, QPixmap, QIcon
from PyQt5.QtWidgets import *

from CropRasterByGrid import CropRasterByGrid


class WindowCropByGrid(QtWidgets.QDialog):
    # 窗口关闭信号槽
    closeEvtSig = pyqtSignal()

    def __init__(self, parent=None):
        QtWidgets.QDialog.__init__(self, parent)
        self.cropRasterByGridThread = None
        self.parent = parent
        self.setObjectName("WindowCropByGrid")
        self.resize(641, 361)
        self.setWindowTitle("根据格网裁剪")
        self.setWindowIcon(QIcon("./images/setup.png"))
        window_pale = QPalette()
        window_pale.setBrush(self.backgroundRole(), QBrush(QPixmap("./images/bg.png")))
        self.setPalette(window_pale)
        # Qt.WindowMaximizeButtonHint |
        self.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowMinimizeButtonHint | Qt.WindowCloseButtonHint)

        self.label = QtWidgets.QLabel(parent=self)
        self.label.setGeometry(QtCore.QRect(40, 100, 100, 20))
        self.label.setObjectName("label")
        self.label.setStyleSheet("color:white")
        self.label.setText("影像文件：")

        self.label_2 = QtWidgets.QLabel(parent=self)
        self.label_2.setGeometry(QtCore.QRect(40, 150, 100, 20))
        self.label_2.setObjectName("label_2")
        self.label_2.setStyleSheet("color:white")
        self.label_2.setText("格网大小：")

        self.label_3 = QtWidgets.QLabel(parent=self)
        self.label_3.setGeometry(QtCore.QRect(40, 200, 100, 20))
        self.label_3.setObjectName("label_3")
        self.label_3.setStyleSheet("color:white")
        self.label_3.setText("存储路径：")

        self.lineEdit = QtWidgets.QLineEdit(parent=self)
        self.lineEdit.setGeometry(QtCore.QRect(150, 100, 370, 21))
        self.lineEdit.setObjectName("lineEdit")

        self.lineEdit_2 = QtWidgets.QLineEdit(parent=self)
        self.lineEdit_2.setGeometry(QtCore.QRect(150, 150, 370, 21))
        self.lineEdit_2.setObjectName("lineEdit_2")

        self.lineEdit_3 = QtWidgets.QLineEdit(parent=self)
        self.lineEdit_3.setGeometry(QtCore.QRect(150, 200, 370, 21))
        self.lineEdit_3.setObjectName("lineEdit_3")

        self.pushButton_2 = QtWidgets.QPushButton(parent=self)
        self.pushButton_2.setGeometry(QtCore.QRect(540, 100, 50, 21))
        self.pushButton_2.setObjectName("pushButton_2")
        self.pushButton_2.setText("选择")
        self.pushButton_2.clicked.connect(self.selectRasterFile)

        self.pushButton_4 = QtWidgets.QPushButton(parent=self)
        self.pushButton_4.setGeometry(QtCore.QRect(540, 200, 50, 21))
        self.pushButton_4.setObjectName("pushButton_4")
        self.pushButton_4.clicked.connect(self.selectOutputDir)
        self.pushButton_4.setText("选择")

        self.pushButton_extract = QtWidgets.QPushButton(parent=self)
        self.pushButton_extract.setGeometry(QtCore.QRect(200, 270, 100, 30))
        self.pushButton_extract.setObjectName("pushButton")
        self.pushButton_extract.clicked.connect(self.extract)
        self.pushButton_extract.setText("裁剪")

        self.pushButton_back = QtWidgets.QPushButton(parent=self)
        self.pushButton_back.setGeometry(QtCore.QRect(350, 270, 100, 30))
        self.pushButton_back.setObjectName("pushButton_back")
        self.pushButton_back.clicked.connect(self.close)
        self.pushButton_back.setText("返回")

        # 创建QSettings，配置文件是tmp/.temp
        self.setting = QSettings('tmp/.temp', QSettings.IniFormat)
        # 设置UTF8编码，反正保存配置文件时出现乱码
        self.setting.setIniCodec('UTF-8')

        # 读取上一次的目录路径
        self.last_path = self.setting.value('LastFilePath')

        # 如果字符串为空，将路径索引到根目录
        if self.last_path is None:
            self.last_path = '/'  # 根盘符
        self.file_path_list = ""

    # 窗体关闭事件
    def closeEvent(self, event) -> None:
        self.closeEvtSig.emit()

    # 选择影像文件
    def selectRasterFile(self):
        filename, _ = QFileDialog.getOpenFileName(self, "选择影像文件", self.last_path, "TIFF(*.tif);;所有文件(*.*)")
        # 如果文件为空，取消后续指令
        if filename is None or len(filename) <= 0:
            return
        try:
            # 将多个文件转为列表
            self.file_path_list = [fname_item for fname_item in filename]

            # 保存当前目录的路径到配置文件中，另外如果不存在'tmp/.temp'文件该函数会自动创建
            self.setting.setValue('LastFilePath', os.path.dirname(self.file_path_list[0]))

            # 将路径设为''程序会使用上一次的路径
            self.last_path = ''

        except Exception as e:
            # 发生异常，弹窗警告
            msg = QtWidgets.QMessageBox.warning(self, "Warning", "选择影像文件%s" % e, buttons=QtWidgets.QMessageBox.Ok,
                                                defaultButton=QtWidgets.QMessageBox.Ok)
        self.lineEdit.setText(filename)

    # 选择存储路径
    def selectOutputDir(self):
        dir = QFileDialog.getExistingDirectory(self, "选择存储路径", self.last_path)
        # 如果文件为空，取消后续指令
        if dir is None or len(dir) <= 0:
            return
        try:
            # 将多个文件转为列表
            self.file_path_list = [fname_item for fname_item in dir]

            # 保存当前目录的路径到配置文件中，另外如果不存在'tmp/.temp'文件该函数会自动创建
            self.setting.setValue('LastFilePath', os.path.dirname(self.file_path_list[0]))

            # 将路径设为''程序会使用上一次的路径
            self.last_path = ''

        except Exception as e:
            # 发生异常，弹窗警告
            msg = QtWidgets.QMessageBox.warning(self, "Warning", "选择存储路径%s" % e, buttons=QtWidgets.QMessageBox.Ok,
                                                defaultButton=QtWidgets.QMessageBox.Ok)

        self.lineEdit_3.setText(dir + "/")

    # 导线提取
    def extract(self):
        if self.lineEdit.text() == "":
            QMessageBox.warning(self, "警告", "影像文件不能为空！", QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
            return
        if self.lineEdit_2.text() == "":
            QMessageBox.warning(self, "警告", "网格大小不能为空！", QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
            return
        if self.lineEdit_3.text() == "":
            QMessageBox.warning(self, "警告", "存储路径不能为空！", QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
            return
        raster_file = self.lineEdit.text()
        grid_size = int(self.lineEdit_2.text())
        out_dir = self.lineEdit_3.text()
        self.pushButton_extract.setEnabled(False)
        self.cropRasterByGridThread = CropRasterByGrid(raster_file, grid_size, out_dir)
        self.cropRasterByGridThread.finishedSig.connect(self.info)
        self.cropRasterByGridThread.errorSig.connect(self.warm)
        self.cropRasterByGridThread.start()
        # super().accept()

    def warm(self, msg):
        self.pushButton_extract.setEnabled(True)
        QMessageBox.warning(self, "警告", msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)

    def info(self, msg):
        self.pushButton_extract.setEnabled(True)
        QMessageBox.information(self, "提示", msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    mainWindow = WindowCropByGrid()
    mainWindow.show()
    sys.exit(app.exec_())
